package com.music.service.music.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.music.dto.basic.UserDTO;
import com.music.mapper.music.SelfCenterMapper;
import com.music.service.music.SelfCenterService;
import com.music.utils.MapSortUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class SelfCenterServiceImpl implements SelfCenterService {

    @Resource
    private SelfCenterMapper selfCenterMapper;
    private final Logger logger = LoggerFactory.getLogger(SelfCenterServiceImpl.class);

    @Override
    public UserDTO getInfo(Long userId) throws Exception {
        return selfCenterMapper.getInfo(userId);
    }

    @Override
    public List<JSONObject> getSingerName(Long userId) throws Exception {
        List<String> singers =  selfCenterMapper.getSingerName(userId);
        List<JSONObject> res = new ArrayList<>();
        HashMap<String,Integer> singerCount = new HashMap<>();
        for(String singer : singers) {
            String[] tmp = singer.split("/");
            for(String t:tmp){
                if(singerCount.containsKey(t)) {
                    singerCount.put(t,singerCount.get(t) + 1);
                } else {
                    singerCount.put(t,1);
                }
            }
        }
        Map<String,Integer> afterSorted = MapSortUtil.sortByValue(singerCount);
        int count = 0;
        JSONObject other = new JSONObject();
        other.put("singer", "其他");
        other.put("count", 0);
        for (Map.Entry<String, Integer> en : afterSorted.entrySet()) {
            if (count < 6) {
                JSONObject a = new JSONObject();
                a.put("singer",en.getKey());
                a.put("count", en.getValue());
                res.add(a);
                count++;
            } else {
                other.put("count", other.getIntValue("count") + en.getValue());
            }
        }
        if (count > 6) {
            res.add(other);
        }
        return res;
    }

    @Override
    public List<JSONObject> getDownloadCount(Long userId) throws Exception {
        return selfCenterMapper.getDownloadCount(userId);
    }
}
